package com.example.administrator.xiaoxiang.fragment.homedetailfragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.administrator.xiaoxiang.R;
import com.example.administrator.xiaoxiang.activity.HomeSecondActivity;
import com.example.administrator.xiaoxiang.adapter.ConvenientBarHolder;
import com.example.administrator.xiaoxiang.adapter.HomeContentAdapter;
import com.example.administrator.xiaoxiang.bean.HomeFragmentBaseBean;
import com.example.administrator.xiaoxiang.bean.HomeFragmentJsonBean;
import com.example.administrator.xiaoxiang.bean.HomeGoodGroupItem;
import com.example.administrator.xiaoxiang.bean.HomeGoodGroups;
import com.example.administrator.xiaoxiang.bean.HomeHeadBean;
import com.example.administrator.xiaoxiang.bean.HomeHotBannerBean;
import com.example.administrator.xiaoxiang.bean.HomeHotBannerItemBean;
import com.example.administrator.xiaoxiang.url.URLResource;
import com.example.administrator.xiaoxiang.utils.AsyncTaskHelper;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * 首页的第一个界面
 */
public class HomeFirstFragment extends Fragment implements
        AsyncTaskHelper.OnDataDownloadListener,SwipeRefreshLayout.OnRefreshListener{

    public static final String TAG = "HomeFirstFragment";
    private AsyncTaskHelper helper;
    private List<HomeFragmentBaseBean> data;
    private HomeContentAdapter adapter;
    private ListView listView;
    private ConvenientBanner convenientBanner;
    private List<HomeHeadBean> headDatas;
    private View view;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean flag;

    public HomeFirstFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home_common, null);
        init(view);
        loadData();
//        listView.setAdapter(adapter);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.e(TAG, "onCreateView: " );
        // Inflate the layout for this fragment
        return view;
    }

    private void loadData() {
        helper.downloadData(URLResource.HomeURL,this);
    }

    private void init(View view) {
        listView = (ListView) view.findViewById(R.id.listView_common_home_fragment);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipRefresh_home_common);
        View headView = LayoutInflater.from(getContext()).inflate(R.layout.item_home_head,listView,false);
        headView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        listView.addHeaderView(headView);
        convenientBanner = (ConvenientBanner) headView.findViewById(R.id.convenientBanner);
        headDatas = new ArrayList<>();
        convenientBanner.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new ConvenientBarHolder();
            }
        },headDatas).setPageIndicator(new int[]{R.drawable.icon02,R.drawable.icon01});
        convenientBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent;
                intent = new Intent(getContext(), HomeSecondActivity.class);
                intent.putExtra("secondUrl",headDatas.get(position).id);
                startActivity(intent);
            }
        });
        helper = new AsyncTaskHelper();
        data = new ArrayList<>();

        adapter = new HomeContentAdapter(data,getContext());
        listView.setAdapter(adapter);
        //下拉刷新的初始化
        flag = false;
        swipeRefreshLayout.setRefreshing(true);
        swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeRefreshLayout.setDistanceToTriggerSync(200);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeColors(Color.RED);
        swipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.WHITE);
    }

    @Override
    public void onDataDownload(byte[] result) {
        String json = new String(result);
//        Log.e("dd", "onDataDownload: "+json );
        Gson gson = new Gson();
        HomeFragmentJsonBean homeFragmentJsonBean = gson.fromJson(json, HomeFragmentJsonBean.class);
        //头
        for (int i = 0; i < homeFragmentJsonBean.getBody().getCarousels().size(); i++) {
            HomeHeadBean homeHeadBean = new HomeHeadBean();
            homeHeadBean.url = homeFragmentJsonBean.getBody().getCarousels().get(i).getThumbnailUrl();
            homeHeadBean.id = homeFragmentJsonBean.getBody().getCarousels().get(i).getId()+".json";
            headDatas.add(homeHeadBean);
        }

        convenientBanner.notifyDataSetChanged();
        //热门推介
        HomeHotBannerBean homeHotBannerBean = new HomeHotBannerBean();
        homeHotBannerBean.titles = homeFragmentJsonBean.getBody().getHotBanner().getTitle();
        for (int i = 0; i < homeFragmentJsonBean.getBody().getHotBanner().getHotBanners().size(); i++) {
            HomeHotBannerItemBean homeHotBannerItemBean = new HomeHotBannerItemBean();
            homeHotBannerItemBean.smallImageUrl = homeFragmentJsonBean.getBody().getHotBanner().getHotBanners().get(i).
                    getSmallImgUrl();
            homeHotBannerItemBean.secondurl = homeFragmentJsonBean.getBody().getHotBanner().getHotBanners().get(i).getId()+"";
            homeHotBannerBean.list.add(homeHotBannerItemBean);
        }
        data.add(homeHotBannerBean);
        //精品分组
        for (int i = 0; i < homeFragmentJsonBean.getBody().getGoodGroups().size(); i++) {
            HomeGoodGroups homeGoodGroups = new HomeGoodGroups();
            homeGoodGroups.thumbnailUrl = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSubject().getThumbnailUrl();
            homeGoodGroups.id = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSubject().getId()+".json";
            for (int j = 0; j < homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().size(); j++) {
                HomeGoodGroupItem homeGoodGroupItem = new HomeGoodGroupItem();
                homeGoodGroupItem.subTitle = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().get(j).getSubTitle();
                homeGoodGroupItem.peroidInstalmentAmount = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().get(j).getPeroidInstalmentAmount();
                homeGoodGroupItem.instalmentPeriods = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().get(j).getInstalmentPeriods()+"";
                homeGoodGroupItem.directPaymentAmount = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().get(j).getDirectPaymentAmount();
                homeGoodGroupItem.thumbnailUrl = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().get(j).getThumbnailUrl();
                homeGoodGroupItem.goodsCode = homeFragmentJsonBean.getBody().getGoodGroups().get(i).getSlideGoods().get(j).getGoodsCode();
                homeGoodGroups.list.add(homeGoodGroupItem);
            }
            data.add(homeGoodGroups);
        }
//        adapter = new HomeContentAdapter(data,getContext());
        if (flag&&swipeRefreshLayout.isRefreshing()) {
            for (int i = 0; i < data.size() / 2; i++) {
                data.remove(i);
            }
        }
        adapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }


    @Override
    public void onResume() {
        super.onResume();
//        Log.e(TAG, "onResume: ");
        convenientBanner.startTurning(3000);
    }

    @Override
    public void onPause() {
        super.onPause();
//        Log.e(TAG, "onPause: ");
        convenientBanner.stopTurning();
    }

    @Override
    public void onRefresh() {
        loadData();
        flag = true;
        swipeRefreshLayout.setRefreshing(true);
    }
}
